package org.groovymud.shell.delegates;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;
import org.groovymud.object.alive.Player;
import org.groovymud.object.registry.Registry;
import org.groovymud.shell.Shell;
import org.groovymud.shell.command.CommandInterpreter;
import org.groovymud.shell.io.TerminalIO;

public class MudRequestDelegate {
	private CommandInterpreter interpreter;
	private Registry registry;
	private Map<Object, Object> shellEnvironment;
	private final static Logger logger = Logger.getLogger(MudRequestDelegate.class);

	public void execute(Player player, TerminalIO terminalIO) throws IOException {
		getInterpreter().doShellCommand("look", player);
		while (getRegistry().getMudObject(player.getName()) != null) {
			handleRequest(player, terminalIO);
		}

	}

	private void handleRequest(final Player player, final TerminalIO io) throws IOException {
		io.write((String) shellEnvironment.get(Shell.PROMPT_VAR));
		io.flush();
		String command;
		try {
			command = io.readln(false);
			getInterpreter().doShellCommand(command, player);
		} catch (Exception e) {
			logger.error(e, e);
			try {
				player.getTerminalOutput().writeln("You cannot do that.");
			} catch (IOException e1) {
				logger.error(e1, e1);
			}

		}
	}

	/**
	 * @param interpreter the interpreter to set
	 */
	public void setInterpreter(CommandInterpreter interpreter) {
		this.interpreter = interpreter;
	}

	/**
	 * @return the interpreter
	 */
	public CommandInterpreter getInterpreter() {
		return interpreter;
	}

	/**
	 * @return the registry
	 */
	public Registry getRegistry() {
		return registry;
	}

	/**
	 * @param registry the registry to set
	 */
	public void setRegistry(Registry registry) {
		this.registry = registry;
	}

	/**
	 * @param environment the environment to set
	 */
	public void setEnvironment(Map<Object, Object> environment) {
		this.shellEnvironment = environment;
	}

	/**
	 * @return the environment
	 */
	public Map<Object, Object> getEnvironment() {
		return shellEnvironment;
	}
}
